//
//  ToDoListTableView.m
//  ToDo
//
//  Created by Zuey But on 27/02/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ItemsTableViewController.h"
#import "ItemDetailViewController.h"
#import "Item.h"

@implementation ItemsTableViewController
@synthesize tableView;
@synthesize addView;
@synthesize newItemTitle;

#pragma mark -
#pragma mark View lifecycle

/*
- (NSString *) saveFilePath{
	NSArray *pathArray =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	return [[pathArray objectAtIndex:0] stringByAppendingPathComponent:@"savedTodo.plist"];
}
- (void) applicationWillTerminate:(UIApplication*)application{
		
	NSArray *values= [[NSArray alloc] initWithObjects:toDo.title];
    [values writeToFile:[self saveFilePath] atomically:YES];
	[values release];
}
 */
- (void)viewDidLoad {
	[super viewDidLoad];
	
    self.title = @"Todo Table";

    // load from plist
    NSString *file = [self dataPath];
    BOOL isFileExist = [[NSFileManager defaultManager] fileExistsAtPath:file];
    
    if (isFileExist) {
        toDoItems = [[NSMutableArray arrayWithContentsOfFile:file] retain];
    }else{
        //NSString *myfile = [[NSBundle mainBundle]pathForResource:@"ToDo-Data" ofType:@"plist"];						
        //toDoItems = [[NSMutableArray alloc] initWithContentsOfFile:myfile];
        toDoItems = [[NSMutableArray alloc] init];
    }
    
    
    // back button
    UIBarButtonItem *backButton  = [[UIBarButtonItem alloc] initWithTitle:@"Back" 
                                                                    style:UIBarButtonItemStylePlain 
                                                                   target:self 
                                                                   action:@selector(backButtonPressed:)];
    self.navigationItem.leftBarButtonItem = backButton;

    // add button
    UIBarButtonItem *addButton  = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd 
                                                                             target:self 
                                                                             action:@selector(addButtonPressed:)];
    self.navigationItem.rightBarButtonItem = addButton;
    
    //hidden the add view
    addView.alpha = 0;
    
    [addButton release];
    [backButton release];
}
/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (NSMutableArray *)toDoItems
{
    
    return toDoItems;
}

-(void)setToDoItems:(NSMutableArray *)item
{
    [item copy];
    [toDoItems release];
    toDoItems = item;
}

#pragma mark -
#pragma mark button action methods

- (NSString *)dataPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
	NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *file = [NSString stringWithFormat:@"%@/data.plist",documentsDirectory];
    
    return file;
}

#pragma mark -
#pragma mark button action methods
- (void)backButtonPressed:(id)sender
{
    [toDoItems writeToFile:[self dataPath] atomically:YES]; 
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)addButtonPressed:(id)sender
{
    NSLog(@"add button pressed");
    [UIView beginAnimations:@"showup" context:nil];
    [UIView setAnimationDuration:0.5];
     addView.alpha = 1;
    [UIView commitAnimations];
}
-(IBAction)cancelButton:(UIButton *)sender
{
    [UIView beginAnimations:@"disappear" context:nil];
    [UIView setAnimationDuration:0.5];

    addView.alpha = 0;
    [UIView commitAnimations];

}
-(IBAction)confirmButton: (UIButton *)sender
{
    // update tablew view
    if (newItemTitle.text!=nil) {
        Item* newItem = [[Item alloc ]initWithTitle:newItemTitle.text];
        [toDoItems insertObject:newItem atIndex:0];  
        [newItem release];
        
        NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:path] withRowAnimation:UITableViewRowAnimationMiddle];

    }
        
    //dismiss view
    [UIView beginAnimations:@"disappear" context:nil];
    [UIView setAnimationDuration:0.5];

    addView.alpha = 0;
    [UIView commitAnimations];

}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return toDoItems.count;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView 
		 cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] 
				 initWithStyle:UITableViewCellStyleDefault 
							   reuseIdentifier:CellIdentifier]autorelease];
    }
    
    // Configure the cell...
	// fill it with contents
    Item* item = [toDoItems objectAtIndex:indexPath.row];
	cell.textLabel.text = item.title;
    
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"rowSelected");
	// Navigation logic may go here. Create and push another view controller.
    
    ItemDetailViewController *detailViewController = [[ItemDetailViewController alloc] initWithNibName:@"ToDoItemDetailViewController" bundle:nil];
    
    // pass data to detail view
    detailViewController.currentItem = (Item *)[toDoItems objectAtIndex:indexPath.row];
    
    // Pass the selected object to the new view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
    
}

- (void)tableView:(UITableView *)tv commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    // If row is deleted, remove it from the list.
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [toDoItems removeObjectAtIndex:indexPath.row];
        
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                              withRowAnimation:UITableViewRowAnimationRight];
    }
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {

    [tableView release];
    [addView release];
    [newItemTitle release];
    
    [super dealloc];

}


@end

